<template>
  <div>
    <el-backtop :right="100" :bottom="200" :visibility-height="10" />
    <!-- 搜索 -->
    <el-space wrap style="margin-bottom:10px">
      <el-select v-model="type" placeholder="请选择广告类型" clearable>
        <el-option v-for="item in otype" :key="item.value" :label="item.name" :value="item.value" />
      </el-select>
      <el-select v-model="status" placeholder="请选择广告状态" clearable>
        <el-option
          v-for="item in ostatus"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-button type="primary" :icon="Search" @click="listData">查找</el-button>
      <el-button type="primary" :icon="Plus" @click="Add">添加</el-button>
    </el-space>
    <!-- 列表 -->
    <el-table :data="tableData" border>
      <el-table-column prop="id" label="广告ID" align="center" />
      <el-table-column prop="title" label="广告标题" align="center" />
      <el-table-column prop="imgUrl" label="广告图片" align="center">
        <template #default="scope">
          <img :src="scope.row.imgUrl" class="el-table-column-img" />
        </template>
      </el-table-column>
      <el-table-column prop="type" label="广告类型" align="center">
        <template #default="scope">
          <el-tag>{{scope.row.type?Atype(scope.row.type):''}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="广告状态" align="center">
        <template #default="scope">
          <el-tag :type="scope.row.status?'success':''">{{scope.row.status?'激活':'冻结'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="unionType" label="关联类型" align="center">
        <template #default="scope">
          <el-tag
            :type="scope.row.unionType?'warning':''"
          >{{scope.row.unionType?AunionType(scope.row.unionType):''}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="unionValue" label="关联值[ID]" align="center" />
      <el-table-column prop="time" label=" 创建时间" align="center">
        <template #default="scope">{{scope.row.gmtCreate?timeformatD(scope.row.gmtCreate):''}}</template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="180">
        <template #default="scope">
          <el-button size="small" type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" @click="handleDelete(scope.$index,scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 修改弹框 -->
    <el-dialog v-model="dialogFormVisible" :title="title">
      <el-form
        :model="form"
        ref="ruleFormRef"
        :rules="rules"
        label-width="120px"
        label-position="left"
      >
        <el-form-item label="广告标题" prop="title">
          <el-input v-model="form.title" autocomplete="off" :disabled="titleF=='编辑'" />
        </el-form-item>
        <el-form-item label="广告类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择优惠券类型" clearable>
            <el-option
              v-for="item in otype"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="广告图片" v-if="form.type">
          <el-upload
            class="avatar-uploader"
            :action="actionUrl"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
            :show-file-list="false"
            :headers="headers"
          >
            <canvas v-show="false" id="canvas" />
            <img v-if="form.imgUrl" :src="form.imgUrl" class="avatar" />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="广告状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-color="form.status==1? '#13ce66':'#ff4949'"
            :inactive-value="0"
            :active-value="1"
          />
        </el-form-item>
        <el-form-item label="关联类型" prop="unionType">
          <el-select
            v-model="form.unionType"
            placeholder="点击时跳转目标"
            clearable
            :disabled="form.type==''"
          >
            <el-option
              v-for="item in ouniontype"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item v-show="form.unionType==1" label="商品" prop="unionValue">
          <el-cascader
            v-model="form.unionValue"
            :options="optionsShop"
            :props="props"
            placeholder="关联至商品"
          />
        </el-form-item>
        <el-form-item v-show="form.unionType==2" label="类目" prop="unionValue">
          <el-cascader
            v-model="form.unionValue"
            :options="optionsCate"
            :props="props"
            placeholder="关联至类目"
          />
        </el-form-item>
        <el-form-item v-show="form.unionType==3" label="关键字" prop="unionValue">
          <el-input
            v-model="form.unionValue"
            autocomplete="off"
            placeholder="点击广告后，用户将得到“此关键字”的商品"
          />
        </el-form-item>
        <el-form-item v-show="form.unionType==4" label="功能页面" prop="unionValue">
          <el-select v-model="form.unionValue" placeholder="请选择一个功能页面" clearable>
            <el-option
              v-for="item in ofun"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="dialogFormVisible=false">取消</el-button>
          <el-button type="primary" @click="fangdou">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 分页 -->
    <dome v-bind="domes" @limits="limits" @pages="pages" />
  </div>
</template>
<script>
import { post, host, action } from "@/util/http";
import dome from "@/components/DomeAndTop.vue";
import { Search, Plus, Download, Delete } from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import timeformatD from "../../../timeformat/formatD";
import Cookies from "js-cookie";
import { debounce } from "@/fangdou/fangdou";//防抖
export default {
  components: {
    dome,
    Plus,
    Delete,
  },
  data() {
    return {
      Search,
      Download,
      Plus,
      // 图片上传路径
      actionUrl: "",
      type: "", //搜索
      status: "", //搜索
      tableData: [], //列表
      dialogFormVisible: false, //布尔值
      title: "", //表单标题
      //  弹框图片请求头
      headers: { AdminToken: Cookies.get("token") },
      // headers: Cookies.get("token"),
      // 商品选择器数据
      optionsShop: [],
      // 类目选择器数据
      optionsCate: [],
      props: {
        value: "id",
        label: "title",
        children: "childrenList",
        emitPath: false,
      },
      // 分页
      domes: {
        limit: 10,
        page: 1,
        total: 10,
      },
      form: {
        type: "",
        unionType: "",
        title: "",
        unionValue: "",
        imgUrl: "",
        color: "",
        status: "",
      },
      //   用户类型
      otype: [
        { value: 1, unionTypes: [1, 2, 3, 4], picRequire: true, name: "轮播" },
        { value: 2, unionTypes: [2], picRequire: true, name: "分类精选" },
        { value: 3, unionTypes: [1, 2, 3, 4], picRequire: true, name: "横幅" },
        {
          value: 4,
          unionTypes: [1, 2, 3, 4],
          picRequire: true,
          name: "首页轮播下5按钮",
        },
        { value: 6, unionTypes: [1, 2, 3, 4], picRequire: false, name: "公告" },
        { value: 9, unionTypes: [1], picRequire: false, name: "商品推荐" },
      ],
      //   关联类型
      ouniontype: [
        { value: 1, name: "商品" },
        { value: 2, name: "类目" },
        { value: 3, name: "关键字" },
        { value: 4, name: "功能页面" },
      ],
      //   功能页面
      ofun: [
        { value: 1, name: "团购列表" },
        { value: 2, name: "优惠券列表" },
      ],
      //   用户状态
      ostatus: [
        {
          value: 0,
          label: "冻结",
        },
        {
          value: 1,
          label: "激活",
        },
      ],
      // 表单规则
      rules: {
        title: [
          {
            required: true,
            message: "广告标题",
            trigger: "blur",
          },
        ],
        type: [
          {
            required: true,
            message: "请选择广告类型",
            trigger: "blur",
          },
        ],
        unionType: [
          {
            required: true,
            message: "请选择关联类型",
            trigger: "blur",
          },
        ],
        // imgUrl: [
        //   {
        //     // required: true,
        //     trigger: "change",
        //   },
        // ],
        status: [
          {
            required: true,
            message: "请选择状态",
            trigger: "blur",
          },
        ],
        unionValue: [
          {
            required: true,
            message: "关联不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.listData();
  },
  methods: {
    timeformatD, // 使用类目名称事件
    // 广告类型事件
    Atype(e) {
      switch (e) {
        case 1:
          return "轮播";
          break;
        case 2:
          return "分类精选";
          break;
        case 3:
          return "横幅";
          break;
        case 4:
          return "首页轮播下5按钮";
          break;
        case 6:
          return "公告";
          break;
        case 9:
          return "商品推荐";
          break;

        default:
          break;
      }
    },
    // 广告类型事件
    AunionType(e) {
      switch (e) {
        case 1:
          return "轮播";
          break;
        case 3:
          return "关键字";
          break;
        case 4:
          return "功能页面";
          break;
        case (6, 2):
          return "类目";
          break;
        case 9:
          return "商品";
          break;

        default:
          break;
      }
    },
    //图片颜色
    getImgColor(img, canvas) {
      console.log(img, canvas, 999);
      canvas.width = img.width;
      canvas.height = img.height;
      let context = canvas.getContext("2d"); //<img> 标签
      context.drawImage(img, 0, 0);
      console.log(img, 99);
      // 获取像素数据
      let data = context.getImageData(0, 0, img.width, img.height).data;
      console.log(context.getImageData(0, 0, img.width, img.height).data);
      let r = 0;
      let g = 0;
      let b = 0;
      // 取所有像素的平均值
      for (var row = 0; row < img.height; row++) {
        for (var col = 0; col < img.width; col++) {
          r += data[(img.width * row + col) * 4];
          g += data[(img.width * row + col) * 4 + 1];
          b += data[(img.width * row + col) * 4 + 2];
        }
      }
      console.log(r, g, b, 11111111111111111111111);
      // 求取平均值
      r = r / (img.width * img.height);
      g = g / (img.width * img.height);
      b = b / (img.width * img.height);
      // 将最终的值取整
      r = Math.round(r);
      g = Math.round(g);
      b = Math.round(b);

      return "rgb(" + r + "," + g + "," + b + ")";
    },
    // 成功上传图片---处理化身成功
    handleAvatarSuccess(res, file) {
      // debugger;
      let { errno, url } = res;
      if (200 == errno) {
        console.log(url, "我要的图片路径");
        this.$nextTick(() => {
          this.form.imgUrl = url;
        });
      } else {
        ElMessage.warning("图片上传失败");
      }
    },
    // 上传之前
    beforeAvatarUpload(rawFile) {
      console.log(11111111);
      if (rawFile.type !== "image/jpeg") {
        ElMessage.error("图片格式必须是jpeg!");
        return false;
      } else if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error("文件大小不能超过2MB!");
        return false;
      }
      return true;
    },
    // 编辑
    handleEdit(e) {
      this.form = {
        type: e.type,
        unionType: e.unionType,
        title: e.title,
        unionValue: e.unionValue,
        imgUrl: e.imgUrl,
        color: e.color,
        status: e.status,
      };
      this.dialogFormVisible = true;
      this.title = "编辑";
      this.categoryData();
    },
    // 添加
    Add() {
      this.dialogFormVisible = true;
      this.title = "创建";
      this.actionUrl = action;
      console.log(this.actionUrl, 2333);
      this.categoryData();
    },
    // 提交
    subMit() {
      let img = document.getElementsByClassName(
        "el-upload-list__item-thumbnail"
      )[0];
      let canvas = document.getElementById("canvas");
      this.$refs.ruleFormRef.validate((valid) => {
        if (valid) {
          // 图片颜色
          if (this.form.imgUrl) {
            this.form.color = this.getImgColor(img, canvas);
            console.log(this.form.color, "图片颜色");
          }
          // 添加的弹框---（创建）
          if (this.form.imgUrl) {
            this.form.color = "rgb(255,255,255)";
          } else {
            this.form.color = "rgb(0.5,0.5,0.5)";
            this.form.imgUrl =
              "http://img.zxwyit.com/admin.shopmall.com/f070c1171e97499a85a1b19956b4911a.png";
          }
          if (this.title == "创建") {
            let data = {
              _gp: "admin.advert",
              _mt: "create",
              ...this.form,
            };
            post(data)
              .then((res) => {
                if (200 == res.data.errno) {
                  this.form = {
                    type: "",
                    unionType: "",
                    title: "",
                    unionValue: "",
                    imgUrl: "",
                    color: "",
                    status: "",
                  };
                  this.dialogFormVisible = false;
                  this.listData();
                  ElMessage.success("创建成功");
                } else {
                  ElMessage.warning(res.data.errmsg);
                }
              })
              .catch((err) => {
                ElMessage.error(err.data.errmsg);
              });
          } else {
            let data = {
              _gp: "admin.advert",
              _mt: "edit",
              ...this.form,
            };
            post(data)
              .then((res) => {
                if (200 == res.data.errno) {
                  this.dialogFormVisible = false;
                  this.listData();
                  console.log(res, "广告修改成功");
                  ElMessage.success("修改成功");
                } else {
                  ElMessage.warning(res.data.errmsg);
                }
              })
              .catch((err) => {
                ElMessage.error(err.data.errmsg);
              });
          }
        } else {
          ElMessage.warning("带星号的必填信息不能为空!");
        }
      });
    },
    fangdou: debounce(function () {
      this.subMit();
    }),
    // 删除
    handleDelete(index, e) {
      console.log(e);
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        center: true,
      })
        .then(() => {
          let data = {
            _gp: "admin.advert",
            _mt: "delete",
            adId: e.id, //广告id
            type: e.type, //广告类型
          };
          post(data).then((res) => {
            if (200 == res.data.errno) {
              this.tableData.splice(index, 1);
              ElMessage.success("删除成功!");
              this.listData();
            }
          });
        })
        .catch(() => {
          ElMessage.info("已取消删除");
        });
    },
    // 类目列表
    categoryData() {
      let data = {
        _gp: "admin.category",
        _mt: "list",
      };
      post(data)
        .then((res) => {
          if (200 == res.data.errno) {
            console.log(res.data.data, "类目");
            this.optionsShop = res.data.data.items;
            this.optionsCate = res.data.data.items;
          } else {
            ElMessage.warning(res.data.errmsg, "111");
          }
        })
        .catch((err) => {
          ElMessage.error(err.data.errmsg);
        });
    },
    listData() {
      let data = {
        _gp: "admin.advert",
        _mt: "list",
        type: this.type,
        status: this.status,
        pageNo: this.domes.page, //当前页码
        limit: this.domes.limit, //页码长度
      };
      post(data)
        .then((res) => {
          if (200 == res.data.errno) {
            this.tableData = res.data.data.items;
            this.domes.total = res.data.data.total;
          } else {
            ElMessage.warning(res.data.errmsg);
          }
        })
        .catch((err) => {
          ElMessage.error(err.data.errmsg);
        });
    },
    limits(e) {
      this.domes.limit = e;
      this.$nextTick(() => {
        this.listData();
      });
    },
    pages(e) {
      this.domes.page = e;
      this.$nextTick(() => {
        this.listData();
      });
    },
  },
};
</script>
<style lang="less" scoped>
// 表单的上传图片
.avatar-uploader {
  width: 178px;
  height: 178px;
}
.avatar-uploader /deep/ .el-upload {
  width: 100%;
  height: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
.el-form-item {
  margin-left: 40px;
  .el-input {
    width: 400px;
  }
}
.el-table-column-img {
  width: 30%;
}
.avatar{
  width: 100%;
  }
</style>